<?php
ini_set('display_errors',1);
set_time_limit(0);
include_once  dirname(dirname(dirname(__FILE__))).'/mgtv_v2/mgtv_init.php';
define('ORG_ID', 'sp_nmgu');
include_once dirname(dirname(dirname(__FILE__))) . '/mgtv_v2/'.ORG_ID.'/init.php';
include_once  dirname(dirname(dirname(__FILE__))).'/mgtv_v2/'.ORG_ID.'/define.php';

$func = isset($_GET['nns_func'])?$_GET['nns_func']:null;
if($func==null){
    //die('param nns_func is empty');
    //$data =  '<result state="0" reason="OK" />';
    _bulid_result('500','param nns_func is empty',null);
}
if(function_exists($func)){
    $func();
}else{
    _bulid_result('500',$func.' not found',null);
}



function get_clip_task(){
    DEBUG && i_write_log_core('------get_clip_task------',ORG_ID.'/clip');
    $nns_new_dir = isset($_GET['nns_new_dir']) ? $_GET['nns_new_dir']:null;
    $task_info = clip_task_model::get_task(ORG_ID);
    if(!is_array($task_info)){
        DEBUG && i_write_log_core('------no task------',ORG_ID.'/clip');
        _bulid_result('404','no task',null);
        exit;
    }   
    $dt = date('Y-m-d H:i:s');
    //更新任务状态:任务已被取走
    $set_state = array(
    'nns_state' => clip_task_model::TASK_C_STATE_HANDLE,
    'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_HANDLE],
    'nns_start_time'=> $dt,
    'nns_modify_time'=>$dt,
    );
    //if($nns_new_dir){
        $set_state['nns_new_dir']=$nns_new_dir;
    //}else{
    //  $set_state['nns_new_dir']=0;
    //}
    clip_task_model::update_task($task_info['nns_id'], $set_state); 
    //任务日志  
    $task_log = array(
    'nns_task_id' => $task_info['nns_id'],
    'nns_state'   => clip_task_model::TASK_C_STATE_HANDLE,
    'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_HANDLE],
    );  
    $rs = clip_task_model::add_task_log($task_log); 
    _bulid_result('200','OK',$task_info['nns_content']);
}


function get_media_url(){
    DEBUG && i_write_log_core('------get_media_url------',ORG_ID.'/clip');
    $task_id = isset($_GET['nns_task_id'])?$_GET['nns_task_id']:null;
    $video_id = isset($_GET['nns_video_id'])?$_GET['nns_video_id']:null;
    $video_type = isset($_GET['nns_video_type'])?$_GET['nns_video_type']:0;
    $nns_index_id = isset($_GET['nns_index_id'])?$_GET['nns_index_id']:null;
    $nns_media_id = isset($_GET['nns_media_id'])?$_GET['nns_media_id']:null;
    $nns_new_dir = isset($_GET['nns_new_dir']) ? $_GET['nns_new_dir']:null;
    //判断任务状态
    $task_info = clip_task_model::get_task_by_id($task_id);
    if($task_info == false){
        DEBUG && i_write_log_core('未找到该任务(task id:'.$task_id.')',ORG_ID.'/clip');       
        _bulid_result('404','get task info fail',null); 
    }
    if($task_info['nns_state'] == clip_task_model::TASK_C_STATE_CANCEL){
        DEBUG && i_write_log_core('任务已取消(task id:'.$task_id.')',ORG_ID.'/clip');        
        $data = '<media id="'.$nns_media_id.'" url="" state="1" reason="task cancel"/>';
        _bulid_result('200','OK',$data);
    }
    //取影片
    $_params = array(
    'nns_video_id'=>$video_id,
    'nns_video_type'=>$video_type,
    'nns_video_index_id'=>$nns_index_id,
    'nns_media_id'=>$nns_media_id
    );
    //i_write_log('params:'.var_export($_params,true));
    $media_info = clip_task_model::get_media_info($_params);
    if($media_info==false){
        DEBUG && i_write_log_core('取片源信息失败',ORG_ID.'/clip');        
        _bulid_result('404','get media info fail',null);
    }   
    include_once dirname(dirname(dirname(dirname(__FILE__)))).'/np/np_http_curl.class.php';
    $http_client = new np_http_curl_class();
    $url = MGTV_MEDIA_DOWNLOAD_URL.'file_id='.$media_info['nns_import_id']; 
    DEBUG && i_write_log_core('从接口取影片下载地址'."\n".$url,ORG_ID.'/clip');
    $result = $http_client->get($url);  
    $ret_arr = json_decode($result, true);
    DEBUG && i_write_log_core('response:'.$result."\n".var_export($ret_arr,true),ORG_ID.'/clip');
    $dt = date('Y-m-d H:i:s');
    if($ret_arr['err']=='0'){
        $down_url = $ret_arr['msg']['download_url'];
        $status = $ret_arr['status'];
        $reason = $ret_arr['reason'];
        $data = '<media id="'.$nns_media_id.'" url="'.$down_url.'" state="0" reason="'.$reason.'"/>';
        $set_state = array(
        'nns_desc'=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_GET_MEDIA_URL_SUCC].'['.$url.'][media_url:'.$down_url.']',
        'nns_state' => clip_task_model::TASK_C_STATE_GET_MEDIA_URL_SUCC,
        'nns_modify_time' => $dt,
        'nns_alive_time' => $dt,
        );
        //if($nns_new_dir){
            $set_state['nns_new_dir']=$nns_new_dir;
        //}else{
        //  $set_state['nns_new_dir']=0;
        //}
        clip_task_model::update_task($task_id, $set_state);     
        //任务日志  
        $task_log = array(
        'nns_task_id'=>$task_id,
        'nns_state'=> clip_task_model::TASK_C_STATE_GET_MEDIA_URL_SUCC,
        'nns_desc'=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_GET_MEDIA_URL_SUCC].'['.$url.'][media_url:'.$down_url.']',
        'nns_create_time' => $dt,
        );
        clip_task_model::add_task_log($task_log);
        _bulid_result('200','OK',$data);
    }else{
        $set_state = array(
        'nns_desc'=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_GET_MEDIA_URL_FAIL].'['.$url.']',
        'nns_state' => clip_task_model::TASK_C_STATE_GET_MEDIA_URL_FAIL,
        'nns_modify_time' => $dt,
        'nns_alive_time' => $dt,
        );
        //if($nns_new_dir){
            $set_state['nns_new_dir']=$nns_new_dir;
        //}else{
            //$set_state['nns_new_dir']=0;
        //}
        clip_task_model::update_task($task_id, $set_state); 
        //任务日志  
        $task_log = array(
        'nns_task_id'=>$task_id,
        'nns_state'=> clip_task_model::TASK_C_STATE_GET_MEDIA_URL_FAIL,
        'nns_desc'=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_GET_MEDIA_URL_FAIL].'['.$url.']',
        'nns_create_time' => $dt,
        'nns_modify_time'=>$dt,
        );
        clip_task_model::add_task_log($task_log);
        _bulid_result('404','get meida url fail',null);
    }
}


//上报切片状态
function report_clip_status(){
    DEBUG && i_write_log_core('------report_clip_status------'."\n params:".var_export($_GET,true),ORG_ID.'/clip');
    $task_id = isset($_GET['nns_task_id'])?$_GET['nns_task_id']:null;
    $state = isset($_GET['nns_state'])?$_GET['nns_state']:null;
    $desc = isset($_GET['nns_desc'])?urldecode($_GET['nns_desc']):null;
    $nns_new_dir = isset($_GET['nns_new_dir']) ? $_GET['nns_new_dir']:null;
    $nns_path = isset($_GET['nns_path']) ? $_GET['nns_path']:null;
    $nns_file_size = isset($_GET['nns_file_size']) ? $_GET['nns_file_size']:null;
    $nns_file_md5 = isset($_GET['nns_file_md5']) ? $_GET['nns_file_md5']:null;
    $nns_cdn_policy = isset($_GET['nns_cdn_policy']) ? $_GET['nns_cdn_policy']:null;
    $nns_file_hit = isset($_GET['nns_file_hit']) ? $_GET['nns_file_hit']:null;
    $dt = date('Y-m-d H:i:s');
    $set_state = array(
    'nns_desc'=>$desc,
    'nns_state' => $state,
    'nns_modify_time' => $dt,
    'nns_alive_time' => $dt,
    );
    $task_info = clip_task_model::get_task_by_id($task_id);
    if($task_info == false){        
        DEBUG && i_write_log_core('未找到该任务(task id:'.$task_id.')',ORG_ID.'/clip');
        _bulid_result('404','get task info fail',null);
        return false;
    }   
    if($task_info['nns_state'] == clip_task_model::TASK_C_STATE_CANCEL){
        DEBUG && i_write_log_core('任务已取消(task id:'.$task_id.')',ORG_ID.'/clip');
        $data = '<result state="1" reason="task cancel" />';
        _bulid_result('200','OK',$data);
    }           
    //如果切片完成，生成注入xml文件，执行影片注入命令
    $state = trim($state);
    if(strtolower($state) == clip_task_model::TASK_C_STATE_OK){
        DEBUG && i_write_log_core('切片完成，生成注入xml文件，执行影片注入命令',ORG_ID.'/clip');
        $nns_date = str_replace('.','',$_GET['nns_date']);
        $nns_date = str_replace('/','',$nns_date);
        $set_state['nns_date'] = $nns_date;     
        $set_state['nns_end_time']=$dt;
        $set_state['nns_file_hit']=$nns_file_hit;
        //在此进行切片任务的上报和如库
    }   
    $set_state['nns_new_dir']=$nns_new_dir;
    clip_task_model::update_task($task_id, $set_state);
    
    if(strtolower($state) == clip_task_model::TASK_C_STATE_OK){
        $queue_task = new   queue_task_model();
        $queue_task->q_clip_ok($task_id);
        
        $queue_task->q_clip_ok_push($task_id,$nns_date,$nns_new_dir,$nns_path,$nns_file_size,$nns_file_md5,$nns_cdn_policy);
    }
    //任务日志  
    $task_log = array(
    'nns_task_id'=>$task_id,
    'nns_state'=>$state,
    'nns_desc'=>$desc,
    'nns_create_time' => $dt,
    );
    clip_task_model::add_task_log($task_log);
    $data =  '<result state="0" reason="OK" />';
    _bulid_result('200','OK',$data);
}


/**
 * 任务不存在或者任务已经注入成功，则可以删除
 */
function delete_clip_file(){
    $task_id = isset($_GET['nns_task_id'])?$_GET['nns_task_id']:null;
    $nns_new_dir = isset($_GET['nns_new_dir']) ? (empty($_GET['nns_new_dir']) ? false : true) : false;
    //if($nns_new_dir){
    //  $result = clip_task_model::can_delete_clip_file($task_id);
    //}else{
        $result = clip_task_model::can_delete_clip_file_new($task_id);//判断分集ID所在的所有任务ID是否可以删除
    //} 
    if($result){
        $data = '<result state="0" reason="allow delete" />';
        _bulid_result('200','OK',$data);
    }else{
        $data =  '<result state="1" reason="not allowed delete" />';
        _bulid_result('200','OK',$data);
    }
}


function _bulid_result($http_code,$resson,$data=null){
    //return 0; 
    header('HTTP/1.1 '.$http_code.' '.$resson);
    header('Status: '.$http_code.' '.$resson);
    header ( "Content-Type:text/xml;charset=utf-8" ); 
    if($data!= null){
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    DEBUG && i_write_log_core('返回结果'."\n".$data,ORG_ID.'/clip');
    echo    $data;      
    }

    exit;
}